<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.actor_id" class="filter-item" style="width: 200px;" placeholder="角色ID" />
      <el-button class="filter-item" type="primary" plain icon="el-icon-search" @click="handleFilter">搜索</el-button>
    </div>
    <div class="">
      <template v-for="(table, tindex) in tableList.baseList">
        <template v-if="tags[tindex]">
          <div :key="'header-' + tindex" class="header">[{{ tags[tindex] }}]</div>
        </template>
        <el-table :key="tindex" v-loading="loading" :data="list" stripe border class="table-content">
          <el-table-column v-for="(column, index) in table" :key="index" :prop="column.prop" :label="column.label" :width="getColumnWidth(column)" :align="column.align || 'center'">
            <template slot-scope="{ row }">
              <span v-if="column.formatter">{{ column.formatter(row) }}</span>
              <el-tag v-else-if="column.tag=='el-tag' && column.prop=='status' && Object.keys(row).length > 0" :type="row.status | statusTagFilter">{{ row.status | statusFilter }}</el-tag>
              <el-tag v-else-if="column.tag=='el-tag' && column.prop=='is_online' && Object.keys(row).length > 0" :type="row.is_online === 1 ? 'success' : 'danger'">{{ row.is_online === 1 ? '在线' : '离线' }}</el-tag>
              <div v-else-if="column.render" v-html="getRenderedContent(column.render, scope)"></div>
              <span v-else>{{ row[column.prop] }}</span>
            </template>
          </el-table-column>
          <template slot="empty">
            <div style="height:35px;line-height:35px;text-align:center;">
            </div>
          </template>
        </el-table>
      </template>
      <div class="col-table">
        <div class="header">[大世界]</div>
        <el-row v-for="(car, tindex) in tableList.carList" :key="tindex" style="display: flex; align-items: stretch;">
          <el-col :span="3">
            <div class="grid-content full-height">{{ car.label }}</div>
          </el-col>
          <el-col :span="21" style="display: flex; flex-direction: column;">
            <el-row :gutter="1">
              <el-col v-for="(field,index) in car.contentList.field" :key="index" :span="3"><div class="grid-content">{{ field }}</div></el-col>
            </el-row>
            <el-row :gutter="1">
              <el-col v-for="(value,index) in car.contentList.value" :key="index" :span="3"><div class="grid-content">{{ value || '--' }}</div></el-col>
            </el-row>
          </el-col>
        </el-row>
      </div>
      <div class="col-table">
        <div class="header">[卡牌英雄]</div>
        <el-row v-for="(hero, hindex) in heroList" :key="hindex" style="display: flex; align-items: stretch;">
          <el-col :span="1">
            <div class="grid-content full-height">{{ hindex + 1 }}</div>
          </el-col>
          <el-col :span="2">
            <div class="grid-content full-height">{{ hero.hero_id }}</div>
          </el-col>
          <el-col :span="24">
            <el-row :gutter="gutter" field="基本信息行" :style="el_row_style">
              <el-col v-for="column in heroBaseOptions" :key="column.prop" :span="hero_cell_span">
                <el-row :gutter="gutter"><el-col :span="hero_cell_span" :style="el_col_content_style"><div class="grid-content2">{{ column.label }}</div></el-col></el-row>
                <el-row :gutter="gutter"><el-col :span="hero_cell_span" :style="el_col_content_style"><div class="grid-content2">
                  <template v-if="column.formatter">
                    {{ column.formatter(hero) }}
                  </template>
                  <template v-else>
                    {{ hero[column.prop] }}
                  </template>
                </div></el-col></el-row>
              </el-col>
            </el-row>
            <el-row v-for="(computeds,index) in computedColumns" :key="index" :gutter="gutter" field="属性行" :style="el_row_style">
              <template v-for="(equipmentColumn,eindex) in computeds">
                <el-col :key="'label-' + index + '-' + eindex" :span="hero_cell_span"><div class="grid-content full-height">{{ equipmentColumn.label }}</div></el-col>
                <el-col v-for="([key, value],pindex) of Object.entries(attrsprop)" :key="index + '-' + eindex + '-' + key + '-' + pindex" :span="key=='attrs'? 4 : hero_cell_span">
                  <template v-if="key==='attrs'">
                    <el-row :gutter="gutter"><el-col :span="4" :style="el_col_content_style"><div class="grid-content2">{{ value }}</div></el-col></el-row>
                    <el-row :gutter="gutter"><el-col :span="4" :style="el_col_content_style"><div class="grid-content2">{{ getNestedValue(hero, equipmentColumn.prop, key) || '' }}</div></el-col></el-row>
                  </template>
                  <template v-else>
                    <el-row :gutter="gutter"><el-col :span="hero_cell_span" :style="el_col_content_style"><div class="grid-content2">{{ value }}</div></el-col></el-row>
                    <el-row :gutter="gutter"><el-col :span="hero_cell_span" :style="el_col_content_style"><div class="grid-content2">{{ getNestedValue(hero, equipmentColumn.prop, key) || '' }}</div></el-col></el-row>
                  </template>
                </el-col>
              </template>
            </el-row>
          </el-col>
        </el-row>
      </div>
    </div>
  </div>
</template>

<script>

import waves from '@/directive/waves'
import { getActorInfo } from '@/api/actorInfo'
import { getServerList } from '@/api/ops'
import actorInfoFields from '@/utils/actor'
import actorHandleMixin from '@/utils/actor_filter'
import actroHeroFields from '@/utils/actorHero'
// import { deepClone } from '@/utils'
export default {
  name: 'ActorInfo',
  components: { },
  directives: { waves },
  mixins: [actorHandleMixin],
  data() {
    return {
      actorInfo: {},
      heroList: [],
      list: [],
      hero_cell_span: 2,
      gutter: 1,
      el_row_style: 'display: flex; align-items: stretch;',
      el_col_style: 'display: flex; flex-direction: column;',
      el_col_content_style: 'display: contents; flex-direction: column;',
      widths: {
        'sid': '70',
        'level': '70',
        'create_dt': '150',
        'login_dt': '150',
        'logout_dt': '150',
        'union_id': '150',
        'total_online_time': '150',
        'update_time': '150',
        'energy_furnace_level': '100',
        'high_draw_guarantee_remain': '120',
        'limit_draw_guarantee_remain': '120'
      },
      tables: [
        ['sid', 'actor_id', 'actor_name', 'account', 'status', 'is_online', 'sex', 'cid', 'game_id', 'login_platform', 'login_game_id', 'best_hero_ids', 'create_dt', 'login_dt', 'logout_dt'],
        ['level', 'item9', 'vip', 'vip_exp', 'total_amount', 'real_amount', 'power', 'hero_num', 'red_hero_num', 'orange_hero_count', 'friend_counts', 'receive_gift_counts', 'union_id', 'total_online_time', 'update_time'],
        ['diamond', 'energy_speed', 'energy', 'material', 'food', 'card_experience', 'voucher_inner', 'voucher_inner_limit', 'voucher_outer', 'voucher_outer_limit',
          'item7', 'item5', 'item8', 'item18', 'item24'
        ],
        ['item11', 'item308011', 'item28', 'item14', 'item12', 'item13'],
        ['guide_event_id', 'main_task_id', 'explore_level_id', 'relic_level_id', 'underground_explore', 'arena_rank', 'town', 'explore_stars', 'relic_remain_count', 'relic_buy_count', 'arena_score', 'arena_remain_count', 'arena_buy_counts', 'arena_box_points'],
        ['fishing_level', 'fishing_bullet_counts', 'fishing_picture_count', 'fossil_level', 'high_draw_guarantee_remain', 'limit_draw_guarantee_remain', 'draw_wish_score'],
        ['energy_furnace_level', 'energy_furnace_stone_counts', 'farm_level', 'farm_plot_count', 'camp_level', 'building_materials_factory_level', 'building_materials_factory_produce_level', 'building_materials_factory_dispatches', 'technology_progress1', 'technology_progress2', 'technology_progress3', 'technology_progress4']
      ],
      tags: ['基本信息', '', '货币数字', '', '玩法相关', '', '建筑相关'],
      heroBaseColumns: ['last_update_time', 'best', 'quality', 'fight', 'level', 'stage', 'star', 'attrs_1', 'attrs_3', 'attrs_5', 'attrs_35', 'weapon_level', 'weapon_stage'],
      attrsprop: { 'uuid': '唯一ID', 'equipId': '道具ID', 'level': '强化等级', 'attrs': '淬炼属性' },
      dlist: [],
      serverList: [],
      loading: false,
      allColumns: actorInfoFields(true, false),
      heroAllColumns: actroHeroFields(0),
      listQuery: {
        sid: '',
        actor_id: ''
      }
    }
  },
  computed: {
    equipmentColumns() {
      return this.heroAllColumns.filter(item => (item.group === 'equipment'))
    },
    runeColumns() {
      return this.heroAllColumns.filter(item => (item.group === 'rune'))
    },
    quenchingColumns() {
      return this.heroAllColumns.filter(item => (item.group === 'quenching'))
    },
    computedColumns() {
      const columns = []
      const cols = [
        ['def_equip_map_1', 'def_equip_map_2'],
        ['def_equip_map_3', 'def_equip_map_4'],
        ['lose_equip_map_1', 'lose_equip_map_2'],
        ['lose_equip_map_3', 'lose_equip_map_4']
      ]
      for (let i = 0; i < cols.length; i++) {
        const col = this.heroAllColumns.filter(item => (cols[i].includes(item.prop)))
        columns.push(col)
      }
      return columns
    },
    heroBaseOptions() {
      const heroBaseOptions = []
      for (let i = 0; i < this.heroBaseColumns.length; i++) {
        const column = this.heroAllColumns.find(item => item.prop === this.heroBaseColumns[i])
        if (column) {
          heroBaseOptions.push(column)
        }
      }
      return heroBaseOptions
    },
    copyList() {
      const copyList = {}
      for (let k = 0; k < this.allColumns.length; k++) {
        if (!this.allColumns[k].group) {
          // console.log(this.allColumns[k])
          continue
        }
        if (this.allColumns[k].group.includes('copy_')) {
          if (!Object.prototype.hasOwnProperty.call(copyList, this.allColumns[k].group)) {
            copyList[this.allColumns[k].group] = []
          }

          copyList[this.allColumns[k].group].push({ ...this.allColumns[k], width: '160' })
        }
      }
      return copyList
    },
    tableList() {
      const tableList = []
      const allFields = this.allColumns.map(item => item.prop)
      let lenindex = 0
      for (let i = 0; i < this.tables.length; i++) {
        tableList[i] = []
        for (let j = 0; j < this.tables[i].length; j++) {
          if (allFields.includes(this.tables[i][j])) {
            tableList[i].push(this.allColumns.find(item => item.prop === this.tables[i][j]))
          }
        }
        lenindex = i
      }
      const carList = []
      for (let d = 1; d <= 3; d++) {
        carList.push({ label: '车队' + d, contentList: { field: [], value: [] }})
      }
      for (const group in this.copyList) {
        if (group === 'copy_car') {
          for (const key in this.copyList[group]) {
            for (const index in carList) {
              if (this.copyList[group][key].label.includes(carList[index].label) && this.actorInfo) {
                carList[index].contentList.field.push(this.copyList[group][key].label)
                carList[index].contentList.value.push(this.actorInfo[this.copyList[group][key].prop] || '')
              }
            }
          }
        } else {
          if (group === 'copy_technology') continue
          lenindex++
          // console.log(this.copyList[group])
          let filtered_base_copy = []
          if (this.copyList[group].length > 0) {
            const prop = this.copyList[group][0].prop
            const result = prop.split('_').slice(0, 2).join('_')
            const base_copy = this.allColumns.filter(item => item.prop.startsWith(result))
            const existingProps = new Set(this.copyList[group].map(col => col.prop))
            filtered_base_copy = base_copy.filter(item => !existingProps.has(item.prop)).map(item => ({ ...item, width: '200' }))
          }
          tableList[lenindex] = [...filtered_base_copy, ...this.copyList[group]]
        }
      }
      console.log(carList)
      return { baseList: tableList, carList: carList }
    }
  },
  created() {
    this.getServerList()
    const id = parseInt(this.$route.params.id)
    const sid = parseInt(this.$route.params.sid)
    if (Number.isFinite(id) && Number.isFinite(sid)) {
      this.listQuery.actor = id
      this.listQuery.sid = sid
      this.getInfo()
    }
  },
  methods: {
    getNestedValue(obj, ...keys) {
      return keys.reduce((acc, key) => {
        return acc && acc[key] !== undefined ? acc[key] : '--'
      }, obj) || '--'
    },
    getColumnWidth(column) {
      if ((!this.widths?.[column.prop]) && column.width && column.width < 90) {
        return '90'
      }
      // 判断 group 是否为 base 或 copy_* 形式
      if (column.group === 'base' || column.group?.startsWith('copy_')) {
        return column.width || '100'
      } else {
        // console.log(column)
        return column.width || this.widths?.[column.prop] || '110'
      }
    },
    async getInfo() {
      const query = this.listQuery
      this.loading = true
      console.log(query)
      const res = await getActorInfo(query)
      this.loading = false
      this.actorInfo = res.data.actorInfo
      if (!this.actorInfo) return
      this.list = [res.data.actorInfo]
      this.heroList = res.data.heroList
      this.$nextTick(() => {
        // this.$refs.table.doLayout()
      })
      // console.log(deepClone(this.allColumns))
    },
    handleFilter(query) {
      this.getInfo()
    },
    async getServerList(params) {
      const query = params
      const res = await getServerList(query)
      this.serverList = res.data.items
      this.loading = false
    }
  }
}
</script>

<style lang="scss" scoped>
  .filter-container .filter-item {
    margin-bottom: 0px;
  }

  .filter-container {
    margin-bottom: 10px;
  }
  .full-height {
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .grid-content {
    background: #fff;
    padding: 10px;
    text-align: center;
    color: #909399;
    font-size: 12px;
    font-weight: 700;
  }
  .grid-content2 {
    background: #fff;
    padding: 10px 0px;
    text-align: center;
    color: #909399;
    font-size: 12px;
    font-weight: 700;
    border-bottom:1px solid #ebeef5;
    width: 100%;
    height: 100%;
    white-space: nowrap;
  }
  .col-table .el-row .el-col {
    border: 1px solid #ebeef5;
    background-color: #fff;
  }
  .header {
    font-weight: 600;
    margin-top: 20px;
    margin-bottom: 6px;
    color: #495060;
  }
</style>
